<template>
  <el-dialog fullscreen title="审核记录填报" v-model="dialogVisible">
    <el-form :disabled="formDisabled" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-descriptions title="" border :column=4>
        <el-descriptions-item label="等级">{{ formData.levelName }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ formData.areaName }}</el-descriptions-item>
        <el-descriptions-item label="审核日期">{{ formData.auditStartDate }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ formData.auditUserName }}</el-descriptions-item>
        <el-descriptions-item label="重要工序" :span="4"> <el-input :disabled="formDisabled" type="textarea"
            v-model="formData.importantProcesses" placeholder="请输入重要工序" /></el-descriptions-item>
        <el-descriptions-item label="近期问题" :span="4"> <el-input :disabled="formDisabled" type="textarea"
            v-model="formData.recentlyProblem" placeholder="请输入近期问题" /></el-descriptions-item>
      </el-descriptions>
    </el-form>
    <ContentWrap>
      <el-table border row-key="id" :data="formData.detailList" :stripe="true" :show-overflow-tooltip="true"
        :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
        <el-table-column label="分类名称" align="center" prop="auditTypeName" width="100" />
        <el-table-column label="审核项" align="center" prop="configName" min-width="300" />
        <el-table-column label="审核结果" align="center" prop="auditResult" width="150">
          <template #default="scope">
            <el-select :disabled="formDisabled" v-model="scope.row.auditResult" placeholder="请选择" clearable>
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.AUDIT_RESULT)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="问题简述" align="center" prop="remark" width="300">
          <template #default="scope">
            <el-input :disabled="formDisabled" type="textarea" v-model="scope.row.remark" placeholder="请输入问题简述" />
          </template>
        </el-table-column>
        <el-table-column label="责任人" align="center" prop="dutyUserId" width="150">
          <template #default="scope">
            <el-select :disabled="formDisabled" clearable filterable v-model="scope.row.dutyUserId"
              placeholder="请选择责任人,支持模糊搜索">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="计划时间" align="center" prop="planDate" width="200">
          <template #default="scope">
            <el-date-picker :disabled="formDisabled" style="width: 100%" v-model="scope.row.planDate" type="date"
              value-format="YYYY-MM-DD" placeholder="计划完成时间" />
          </template>
        </el-table-column>

        <el-table-column label="附件" min-width="320px" align="center">
          <template #default="scope">
            <UploadFile :isShowTip="false" v-model="scope.row.files" :disabled="formDisabled" />
          </template>
        </el-table-column>

      </el-table>
    </ContentWrap>

    <!-- 打印按钮（在操作按钮区域添加） -->
    <template #footer>
      <el-button :disabled="formDisabled" @click="submitForm(1)" type="primary">暂 存</el-button>
      <el-button :disabled="formDisabled" @click="submitForm(2)" type="primary">提 交</el-button>
      <!-- 添加打印按钮 -->
      <el-button @click="showPrintPreview" type="success">打印</el-button>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>

  <!-- 打印预览对话框 -->
  <el-dialog v-model="printPreviewVisible" title="打印预览" width="90%" :close-on-click-modal="false"
    :close-on-press-escape="false" :before-close="handlePreviewClose" class="print-preview-dialog">



    <!-- 审核明细 -->
    <div class="print-section">
      <h2>审核明细</h2>
      <el-table :data="formData.detailList" border :show-overflow-tooltip="true">
        <el-table-column label="分类名称" align="center" prop="auditTypeName" width="100" />
        <el-table-column label="审核项" align="center" prop="configName" min-width="250" />
        <el-table-column label="审核结果" align="center" prop="auditResult" width="120">
          <template #default="{ row }">
            {{ getAuditResultLabel(row.auditResult) }}
          </template>
        </el-table-column>
        <el-table-column label="问题简述" align="center" prop="remark" width="250">
          <template #default="{ row }">
            {{ row.remark || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="责任人" align="center" prop="dutyUserName" width="150">
          <template #default="{ row }">
            {{ row.dutyUserName || '未指定' }}
          </template>
        </el-table-column>
        <el-table-column label="计划时间" align="center" prop="planDate" width="150">
          <template #default="{ row }">
            {{ row.planDate }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="print-actions">
        <el-button type="primary" @click="printPreview">打印</el-button>
        <el-button @click="printPreviewVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getIntDictOptionsString } from '@/utils/dict'
import { AuditPlanAreaApi, AuditPlanArea } from '@/api/business/auditplanarea'
import * as UserApi from '@/api/system/user'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

/** 审核计划区域 表单 */
defineOptions({ name: 'AuditPlanAreaForm' })

// 用户列表
const userList = ref([])

const initUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  levelId: undefined,
  planId: undefined,
  areaId: undefined,
  auditStartDate: undefined,
  auditEndDate: undefined,
  auditUserId: undefined,
  status: undefined,
  areaName: undefined,
  importantProcesses: undefined,
  recentlyProblem: undefined,
  writeUserId: undefined,
  writeUserName: undefined,
  writeTime: undefined,
  sendUserId: undefined,
  sendUserName: undefined,
  sendTime: undefined,
  auditUserName: undefined,
  writeStatus: undefined,
  levelName: undefined,
  detailList: []
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const formDisabled = ref(false)

// 打印预览相关
const printPreviewVisible = ref(false)
const printPreviewContent = ref<HTMLElement | null>(null)
const currentTime = computed(() => {
  const now = new Date()
  return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  if (type == 'view') {
    formDisabled.value = true
  } else {
    formDisabled.value = false
  }

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AuditPlanAreaApi.getAuditPlanArea(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type) => {
  if (type == 1) {
    //暂存
  } else if (type == 2) {
    //提交
    formData.value.writeStatus = type
  }

  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true

  const valid = validateAuditPlanAreas(formData.value.detailList)
  if (!valid) {
    return // 校验失败，阻止后续操作
  }

  try {
    const data = formData.value as unknown as AuditPlanArea
    if (formType.value === 'create') {
      await AuditPlanAreaApi.createAuditPlanArea(data)
      message.success(t('common.createSuccess'))
    } else {
      await AuditPlanAreaApi.updateAuditPlanArea(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 校验函数
function validateAuditPlanAreas(detailList) {
  for (let i = 0; i < detailList.length; i++) {
    const item = detailList[i]
    // 如果审核不通过的 需要添加责任人 计划时间
    if (item.auditResult != 'Y') {
      if (item.dutyUserId == undefined || item.dutyUserId == null) {
        ElMessage.error(`第 ${i + 1} 行：请选择责任人`)
        return false
      }

      if (item.planDate == undefined || item.planDate == null) {
        ElMessage.error(`第 ${i + 1} 行：请选择计划完成时间`)
        return false
      }
    }
  }

  return true // 全部通过
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    levelId: undefined,
    planId: undefined,
    areaId: undefined,
    auditStartDate: undefined,
    auditEndDate: undefined,
    auditUserId: undefined,
    status: undefined,
    areaName: undefined,
    importantProcesses: undefined,
    recentlyProblem: undefined,
    writeUserId: undefined,
    writeUserName: undefined,
    writeTime: undefined,
    sendUserId: undefined,
    sendUserName: undefined,
    sendTime: undefined,
    auditUserName: undefined,
    levelName: undefined,
    detailList: []
  }
  formRef.value?.resetFields()
}

/** 获取审核结果标签 */
const getAuditResultLabel = (value: string) => {
  const options = getIntDictOptionsString(DICT_TYPE.AUDIT_RESULT)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

/** 显示打印预览 */
const showPrintPreview = () => {
  printPreviewVisible.value = true
  // 确保内容渲染完成
  nextTick(() => {
    printPreviewContent.value = document.getElementById('print-preview-content')
  })
}

/** 关闭打印预览 */
const handlePreviewClose = () => {
  printPreviewVisible.value = false
}

/** 打印预览内容 */
const printPreview = () => {
  if (!printPreviewContent.value) return

  // 使用 html2canvas 生成图片
  html2canvas(printPreviewContent.value, {
    scale: 2, // 提高分辨率
    useCORS: true, // 解决跨域问题
    logging: false,
    dpi: 300, // 提高打印质量
    backgroundColor: null
  }).then(canvas => {
    const imgData = canvas.toDataURL('image/png')

    // 创建 PDF
    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: 'a4'
    })

    // 计算 PDF 尺寸
    const imgWidth = 210 // A4宽度(8.27英寸)
    const pageHeight = 297 // A4高度(11.69英寸)
    const imgHeight = canvas.height * imgWidth / canvas.width

    // 添加图片到 PDF
    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)

    // 保存 PDF 并自动打印
    pdf.save(`审核报告_${currentTime.value}.pdf`)
    pdf.autoPrint()
    pdf.output('dataurlnewwindow')

    // 关闭预览
    printPreviewVisible.value = false
  })
}

/** 初始化 **/
onMounted(async () => {
  initUserList()
})
</script>

<style scoped>
.print-container {
  position: relative;
}

.print-header {
  text-align: center;
  margin-bottom: 20px;
}

.print-section {
  margin-bottom: 25px;
}

.print-content {
  line-height: 1.6;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  margin-top: 5px;
}

.print-actions {
  text-align: center;
  margin-top: 20px;
}

.print-preview-dialog {
  .el-dialog__body {
    padding: 20px 30px;
  }
}

/* 为打印预览添加打印样式 */
@media print {
  .print-container {
    display: none;
  }

  .print-preview-dialog {
    display: none !important;
  }

  #print-preview-content {
    display: block !important;
  }
}
</style>
